<template>
  <div class="pagebg">
    <h1>证书分类</h1>
    <!-- 输入框 -->
    <div class="searchbox">
      <div>
        <el-input
          style="width: 240px; margin-right: 20px"
          v-model="cardName"
          placeholder="请输入证书名称"
          :suffix-icon="Search"
          @input="searchinp"
        />
        <el-button @click="chongzhi">重置</el-button>
      </div>
      <!-- 新增按钮 -->
      <div>
        <el-button type="primary" color="#0052CC" @click="addon"
          >新增</el-button
        >
      </div>
    </div>

    <!-- 表格区域 -->
    <div>
      <el-table
        :data="
          tableData.slice((currentPage - 1) * pageSize, currentPage * pageSize)
        "
        border
        stripe
        style="width: 100%"
        :header-cell-style="{ textAlign: 'center' }"
        :cell-style="{ textAlign: 'center' }"
        v-loading="loading"
        show-overflow-tooltip
      >
        <el-table-column prop="id" label="序号" width="60" />
        <el-table-column prop="title" label="分类名称" />
        <el-table-column prop="create_time" label="添加时间" />
        <el-table-column prop="update_time" label="更新时间" />
        <el-table-column label="操作">
          <template v-slot="scope">
            <el-button type="primary" @click="editbox(scope.row.id)"
              >编辑</el-button
            >
            <el-button
              type="danger"
              @click="delbtn(scope.row.id, scope.row.title)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="pageBox">
      <el-pagination
        v-model:current-page="currentPage"
        v-model:page-size="pageSize"
        :page-sizes="[10, 20, 30, 50]"
        :small="small"
        :disabled="disabled"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="tableDatalen"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加、编辑 弹窗 -->

    <el-dialog
      v-model="dialogFormVisible"
      :title="modelTitle"
      style="position: relative"
      :close-on-click-modal="false"
      align-center
    >
      <el-form :model="form" :rules="rules" ref="ruleFormRef">
        <el-form-item
          label="分类名称"
          :label-width="formLabelWidth"
          prop="title"
        >
          <el-input
            v-model="form.title"
            autocomplete="off"
            placeholder="请选择分类名称"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button type="primary" @click="btnsure"> 确认 </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 删除确认弹窗 -->
    <el-dialog v-model="deshow" title="提示" width="30%" align-center>
      <span style="display: flex"
        ><img class="jinggao" src="../../assets/img/jianggao.png" />确定删除{{
          showtitle
        }}？</span
      >
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="deshow = false">取消</el-button>
          <el-button type="primary" @click="delsure"> 删除 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
defineOptions({
  // name 作为一种规范最好必须写上并且和路由的name保持一致
  name: "cardType"
});
import { ref, reactive, toRaw } from "vue";
import { Calendar, Search } from "@element-plus/icons-vue";
import { itemList, addItem, delItem } from "@/api/cardType";
import { ElMessage } from "element-plus";
import { ElNotification } from "element-plus";
// 加载效果
const loading = ref(false);
// 菜单选项
const cardName = ref("");

const tableData = ref([]);
renders();
function renders() {
  new Promise((resolve, reject) => {
    itemList()
      .then(data => {
        tableData.value = JSON.parse(data).data;
        console.log(tableData.value);
        tableDatalen.value = tableData.value.length;
      })
      .catch(error => {
        reject(error);
      });
  });
}

// ----------------------模糊搜索----------------------
let searchinp = () => {
  let datas = tableData.value;
  tableData.value = datas.filter(function (item) {
    if (String(item.title).indexOf(String(cardName.value)) > -1) {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 1200);
      return item;
    } else {
      loading.value = true;
      setTimeout(() => {
        loading.value = false;
      }, 1200);
      tableData.value = [];
    }
  });
};
let chongzhi = () => {
  // clearVal();
  loading.value = true;
  setTimeout(() => {
    loading.value = false;
  }, 800);
  renders();
  cardName.value = "";
  // status.value = "";
};
// -----------------------------添加、编辑弹窗--------------------------------
const form = reactive({
  title: ""
});
const btnStatus = ref(0);
const dialogFormVisible = ref(false);
const formLabelWidth = "140px";
const modelTitle = ref("添加证书");

let addon = () => {
  dialogFormVisible.value = true;
  btnStatus.value = 1;
  modelTitle.value = "添加证书";
};
const edid = ref();
let editbox = id => {
  edid.value = id;
  btnStatus.value = 2;
  modelTitle.value = "编辑证书";
  dialogFormVisible.value = true;
};
// 校验规则
const ruleFormRef = ref(null);
const rules = {
  title: [{ required: true, message: "请完善证书名称", trigger: "blur" }]
};

let btnsure = () => {
  ruleFormRef.value.validate(valid => {
    if (!valid) return ElMessage.error("请将内容填写完成后 再进行添加操作!");

    if (btnStatus.value == 1) {
      // 添加
      let addobj = {
        title: form.title
      };
      new Promise((resolve, reject) => {
        addItem(addobj)
          .then(res => {
            resolve(res);
            console.log(JSON.parse(res));
            if (JSON.parse(res).code == 1) {
              ElNotification({
                title: "Success",
                message: "添加成功",
                type: "success"
              });
              dialogFormVisible.value = false;
              loading.value = true;
              setTimeout(() => {
                loading.value = false;
                renders();
              }, 800);
            } else {
              ElNotification({
                title: "Error",
                message: "操作失败",
                type: "error"
              });
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    } else {
      // 编辑
      let editobj = {
        id: edid.value,
        title: form.title
      };
      new Promise((resolve, reject) => {
        addItem(editobj)
          .then(res => {
            resolve(res);
            console.log(JSON.parse(res));
            if (JSON.parse(res).code == 1) {
              ElNotification({
                title: "Success",
                message: "操作成功",
                type: "success"
              });
              dialogFormVisible.value = false;
              loading.value = true;
              setTimeout(() => {
                loading.value = false;
                renders();
              }, 800);
            } else {
              ElNotification({
                title: "Error",
                message: "操作失败",
                type: "error"
              });
            }
          })
          .catch(error => {
            reject(error);
          });
      });
    }
  });
};
// -----------------------------删除-------------------------------
const delid = ref<any>();
const deshow = ref(false);
const showtitle = ref<any>();
let delbtn = (deid, deltitle) => {
  delid.value = deid;
  deshow.value = true;
  showtitle.value = deltitle;
  console.log(showtitle.value, delid.value);
}
let delsure = () => {
  new Promise((resolve, reject) => {
    delItem({ id: delid.value })
      .then(res => {
        console.log(JSON.parse(res));
        if (JSON.parse(res).code == 1) {
          ElNotification({
            title: "Success",
            message: "操作成功",
            type: "success"
          });
          deshow.value = false;
          loading.value = true;
          setTimeout(() => {
            loading.value = false;
            renders();
          }, 800);
        } else {
          ElNotification({
            title: "Error",
            message: "操作失败",
            type: "error"
          });
        }
      })
      .catch(error => {
        reject(error);
      });
  });
};
// ----------------------------------------------------------------------------
const currentPage = ref<any>(1);
const pageSize = ref(10);
const small = ref(false);
const background = ref(false);
const disabled = ref(false);
const tableDatalen = ref();
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
};
</script>

<style lang="scss" scoped>
h1 {
  font-weight: 400;
}
.pagebg {
  width: auto;
  height: 100%;
  background-color: #ffffff;
}
.searchbox {
  width: auto;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}
.pageBox {
  width: 100%;
  height: 50px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.jinggao {
  width: 20px;
  height: 20px;
  margin-right: 5px;
}
</style>
